package demo.controller;

import demo.mapper.UserInfoMapper;
import demo.pojo.RegisterRequest;
import demo.pojo.response.Result;
import demo.utils.RegexUtil;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import demo.BlogUserApi;
import demo.pojo.UserInfoRequest;
import demo.pojo.UserLoginResponse;
import demo.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@SuppressWarnings("ALL")
@Slf4j
@RequestMapping("/blog-user-info")
@RestController
public class UserController implements BlogUserApi {

    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;

    public Result<UserLoginResponse> login(@Validated @RequestBody UserInfoRequest user){
        log.info("用户登录, userName: {}", user.getUserName());
        return Result.success(userService.login(user));
    }

    public Result<UserLoginResponse> getUserInfo(@NotNull Integer userId) {
        return Result.success(userService.getUserInfo(userId));
    }

    public Result<UserLoginResponse> getAuthorInfo(@NotNull Integer blogId){
        return Result.success(userService.selectAuthorInfoByBlogId(blogId));
    }

    @Override
    public Result<Integer> register(RegisterRequest request) {
        log.info("register 收到请求： {}", request);

        String s = verifyInfo(request);
        if (s != null) {
            return Result.fail(s);
        }

        Integer id =  userService.register(request);

        return Result.success(id);
    }

    private String verifyInfo(RegisterRequest request) {
        if (!RegexUtil.checkURL(request.getGithubUrl())) {
            return "githubUrl格式错误";
        }
        if (!RegexUtil.checkMail(request.getEmail())) {
            return "Email格式错误";
        }
        return null;
    }

}
